package com.xluomo.notification_listen_service_plugin;

import static com.xluomo.notification_listen_service_plugin.NotificationListenUtil.isPermissionGranted;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import io.flutter.Log;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;


public class NotificationListenServicePlugin implements FlutterPlugin, MethodCallHandler, EventChannel.StreamHandler {

    private static final String CHANNEL_TAG = "com.xluomo/notifications_channel";
    private static final String EVENT_TAG = "com.xluomo/notifications_event";

    private MethodChannel channel;
    private EventChannel eventChannel;
    private Context context;

    private NotificationEventService notificationEventService;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        context = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), CHANNEL_TAG);
        channel.setMethodCallHandler(this);
        eventChannel = new EventChannel(flutterPluginBinding.getBinaryMessenger(), EVENT_TAG);
        eventChannel.setStreamHandler(this);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case "isPermissionGranted":
                result.success(isPermissionGranted(context));
                break;
            case "requestPermission":
                try {
                    Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
                    context.startActivity(intent);
                    result.success(true);
                } catch (Exception e) {
                    Log.i("flutter", e.toString());
                    result.success(false);
                }
                break;
            case "sendNotification":
                sendNotification(call);
                break;
            default:
                Log.i("flutter", call.method);
                result.notImplemented();
                break;
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
        eventChannel.setStreamHandler(null);
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(NotificationVars.INTENT);
        notificationEventService = new NotificationEventService(events);
        context.registerReceiver(notificationEventService, intentFilter);

        Intent intent = new Intent(context, NotificationListenService.class);
        context.startService(intent);
        Log.i("flutter", "NotificationListenService start");
    }

    @Override
    public void onCancel(Object arguments) {
        context.unregisterReceiver(notificationEventService);
        notificationEventService = null;
    }

    private int icons(Intent intent) {
        String iconName = intent.getStringExtra("iconName");
        String iconType = intent.getStringExtra("iconType");
        if (iconName == null || iconName.isEmpty()) iconName = "ic_launcher";
        if (iconType == null || iconType.isEmpty()) iconType = "mipmap";
        return context.getResources().getIdentifier(iconName, iconType, context.getPackageName());
    }

    private void sendNotification(MethodCall call) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(
                "CHANNEL_ID",
                "Your Channel Name",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        notificationManager.createNotificationChannel(channel);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNEL_ID")
                .setSmallIcon(icons(new Intent()))
                .setContentTitle(call.argument("title")) // 设置通知标题
                .setContentText(call.argument("content")) // 设置通知内容
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        notificationManager.notify(95872, builder.build());
    }
}